package com.huanglj.taobaounion.presenter.implement;

import android.util.Log;

import com.huanglj.taobaounion.model.api.Api;
import com.huanglj.taobaounion.model.domain.TicketParams;
import com.huanglj.taobaounion.model.domain.TicketResult;
import com.huanglj.taobaounion.presenter.ITicketPresenter;
import com.huanglj.taobaounion.utils.LogUtil;
import com.huanglj.taobaounion.utils.RetrofitManager;
import com.huanglj.taobaounion.utils.UrlUtils;
import com.huanglj.taobaounion.view.ITicketCallBack;

import java.net.HttpURLConnection;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class TicketPresenterImpl implements com.huanglj.taobaounion.presenter.ITicketPresenter {

    private static final String TAG = "TicketPresenterImpl";
    private ITicketCallBack mCallBack;

    @Override
    public void getTicket(String title, String url, String cover) {
        //TODO:获取淘口令
        Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
        Api api = retrofit.create(Api.class);
        String ticketPath = UrlUtils.getTicketPath(url);
        TicketParams ticketParams = new TicketParams(ticketPath,title);

        api.getTicketCommand(ticketParams).enqueue(new Callback<TicketResult>() {
            @Override
            public void onResponse(Call<TicketResult> call, Response<TicketResult> response) {
                LogUtil.d(TAG,"responseCode: " + response.code());
                if (response.code()== HttpURLConnection.HTTP_OK){
                    TicketResult body = response.body();
                    handleTicket(body,cover);
                    LogUtil.d(TAG,"Msg--->"+body.getMessage()+"\n"+"model--->"+body.toString());
                }

            }

            @Override
            public void onFailure(Call<TicketResult> call, Throwable t) {
                LogUtil.d(TAG,"failure--->" +t.toString());
            }
        });
    }

    private void handleTicket(TicketResult result, String cover) {
        if(mCallBack != null) {
            String model = result.getData().getTbk_tpwd_create_response().getData().getModel();
            if (model == null) {
                mCallBack.onEmpty();
            }else {
                mCallBack.onTicketLoaded(cover,result);
            }
        }


    }

    @Override
    public void registerViewCallBack(ITicketCallBack callBack) {
        this.mCallBack = callBack;
    }

    @Override
    public void unregisterViewCallBack(ITicketCallBack callBack) {
        mCallBack = null;
    }
}
